import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
  Card,
  CardMedia,
  Typography,
  Avatar,
  IconButton,
  CircularProgress,
  Button,
  Box,
  LinearProgress
} from '@mui/material';
import {
  Favorite,
  FavoriteBorder,
  Comment,
  Visibility,
  Share,
  PlayArrow,
  Pause,
  VolumeOff,
  VolumeUp
} from '@mui/icons-material';
import { RecommendationContent, RecommendationContentType } from '../../../types/recommendation/recommendation';
import { TargetType } from '../../../types/interaction/interaction';
import { useInteraction } from '../../../hooks/useInteraction';
import { formatNumber } from '../../../utils/recommendation';
import { ImageCarousel } from '../../../components';
import styles from './RecommendationCard.module.css';

interface RecommendationCardProps {
  content: RecommendationContent;
  isActive: boolean;
  onError?: (error: string) => void;
}

const RecommendationCard: React.FC<RecommendationCardProps> = ({
  content,
  isActive,
  onError
}) => {
  const [isLiked, setIsLiked] = useState(content.isLiked);
  const [likeCount, setLikeCount] = useState(content.likeCount);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(true);
  const [progress, setProgress] = useState(0);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [showControls, setShowControls] = useState(false);
  const [controlsTimer, setControlsTimer] = useState<NodeJS.Timeout | null>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  
  const { toggleLike, loading: likeLoading } = useInteraction();

  // 显示控制界面
  const showVideoControls = () => {
    if (controlsTimer) {
      clearTimeout(controlsTimer);
      setControlsTimer(null);
    }
    setShowControls(true);
  };

  // 隐藏控制界面（延迟）
  const hideVideoControls = () => {
    const timer = setTimeout(() => {
      setShowControls(false);
    }, 2000); // 2秒后隐藏
    setControlsTimer(timer);
  };

  // 清理定时器
  useEffect(() => {
    return () => {
      if (controlsTimer) {
        clearTimeout(controlsTimer);
      }
    };
  }, [controlsTimer]);

  // 处理视频播放控制
  useEffect(() => {
    if (content.contentType === RecommendationContentType.VIDEO && videoRef.current) {
      if (isActive) {
        videoRef.current.play().catch(console.error);
        setIsPlaying(true);
        // 播放时延迟隐藏控制界面
        hideVideoControls();
      } else {
        videoRef.current.pause();
        setIsPlaying(false);
        // 暂停时清除隐藏定时器
        if (controlsTimer) {
          clearTimeout(controlsTimer);
          setControlsTimer(null);
        }
      }
    }
  }, [isActive, content.contentType]);

  // 视频事件监听
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      const current = video.currentTime;
      const total = video.duration;
      setCurrentTime(current);
      if (total) {
        setProgress((current / total) * 100);
      }
    };

    const handleLoadedMetadata = () => {
      setDuration(video.duration);
    };

    const handleEnded = () => {
      setIsPlaying(false);
      setProgress(0);
      setCurrentTime(0);
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('loadedmetadata', handleLoadedMetadata);
    video.addEventListener('ended', handleEnded);

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
      video.removeEventListener('ended', handleEnded);
    };
  }, []);

  // 处理点赞
  const handleLike = async () => {
    if (likeLoading) return;
    
    try {
      const result = await toggleLike({
        targetId: content.id,
        targetType: TargetType.CONTENT
      });
      if (result) {
        setIsLiked(!isLiked);
        setLikeCount(prev => isLiked ? prev - 1 : prev + 1);
      }
    } catch (error) {
      console.error('点赞失败:', error);
      onError?.('点赞失败，请稍后重试');
    }
  };

  // 处理视频播放/暂停
  const handleVideoToggle = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
        // 暂停时清除隐藏定时器，保持控制界面显示
        if (controlsTimer) {
          clearTimeout(controlsTimer);
          setControlsTimer(null);
        }
      } else {
        videoRef.current.play().catch(console.error);
        setIsPlaying(true);
        // 播放时延迟隐藏控制界面
        hideVideoControls();
      }
    }
  };

  // 处理静音切换
  const handleMuteToggle = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  // 处理进度条点击
  const handleProgressClick = (event: React.MouseEvent<HTMLDivElement>) => {
    if (!videoRef.current || !duration) return;
    
    const rect = event.currentTarget.getBoundingClientRect();
    const clickX = event.clientX - rect.left;
    const percentage = clickX / rect.width;
    const newTime = percentage * duration;
    
    videoRef.current.currentTime = newTime;
    setCurrentTime(newTime);
    setProgress(percentage * 100);
    
    // 显示控制界面
    showVideoControls();
  };

  // 处理键盘快进后退
  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    if (!videoRef.current || !duration || content.contentType !== RecommendationContentType.VIDEO) return;
    
    // 只在视频激活时响应键盘事件
    if (!isActive) return;
    
    let newTime = currentTime;
    
    switch (event.key) {
      case 'ArrowLeft':
        // 左键后退5秒
        event.preventDefault();
        newTime = Math.max(0, currentTime - 5);
        break;
      case 'ArrowRight':
        // 右键快进5秒
        event.preventDefault();
        newTime = Math.min(duration, currentTime + 5);
        break;
      case ' ':
        // 空格键播放/暂停
        event.preventDefault();
        handleVideoToggle();
        return;
      default:
        return;
    }
    
    videoRef.current.currentTime = newTime;
    setCurrentTime(newTime);
    setProgress((newTime / duration) * 100);
    
    // 显示控制界面
    showVideoControls();
  }, [currentTime, duration, content.contentType, isActive, handleVideoToggle, showVideoControls]);

  // 绑定键盘事件
  useEffect(() => {
    if (isActive && content.contentType === RecommendationContentType.VIDEO) {
      window.addEventListener('keydown', handleKeyDown);
      return () => window.removeEventListener('keydown', handleKeyDown);
    }
    return undefined;
  }, [isActive, content.contentType, handleKeyDown]);

  // 格式化时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // 处理分享
  const handleShare = async () => {
    try {
      if (navigator.share) {
        await navigator.share({
          title: content.title,
          text: content.textContent,
          url: window.location.href
        });
      } else {
        // 复制到剪贴板
        await navigator.clipboard.writeText(window.location.href);
        // 这里可以添加一个提示
      }
    } catch (error) {
      console.error('分享失败:', error);
    }
  };

  // 渲染媒体内容
  const renderMedia = () => {
    if (content.contentType === RecommendationContentType.IMAGE) {
      // 构建图片轮播数组
      const allImages: string[] = [];
      
      // 如果有封面，将封面作为第一张图片
      if (content.coverUrl) {
        allImages.push(content.coverUrl);
      }
      
      // 添加内容图片，但避免重复
      if (content.images && content.images.length > 0) {
        content.images.forEach(image => {
          if (!allImages.includes(image.imageUrl)) {
            allImages.push(image.imageUrl);
          }
        });
      }
      
      if (allImages.length > 0) {
        return (
          <ImageCarousel
            images={allImages}
            alt={content.title}
            height="100%"
            width="100%"
            objectFit="cover"
            showIndicators={true}
            showNavigation={true}
            borderRadius={0}
          />
        );
      }
    } else if (content.contentType === RecommendationContentType.VIDEO) {
      if (content.videos && content.videos.length > 0) {
        return (
          <div 
            className={styles.videoContainer}
            onMouseEnter={showVideoControls}
            onMouseLeave={hideVideoControls}
          >
            <video
              ref={videoRef}
              src={content.videos[0].videoUrl}
              className={styles.video}
              loop
              muted={isMuted}
              playsInline
              onClick={handleVideoToggle}
              poster={content.coverUrl}
            />
            
            {/* 视频控制按钮 */}
            <div 
              className={`${styles.videoControls} ${showControls || !isPlaying ? styles.visible : ''}`}
              onMouseEnter={showVideoControls}
              onMouseLeave={hideVideoControls}
            >
              <IconButton
                onClick={handleVideoToggle}
                className={styles.playButton}
              >
                {isPlaying ? <Pause /> : <PlayArrow />}
              </IconButton>
              
              <IconButton
                onClick={handleMuteToggle}
                className={styles.muteButton}
              >
                {isMuted ? <VolumeOff /> : <VolumeUp />}
              </IconButton>
            </div>
            
            {/* 播放进度条 */}
            <div 
              className={`${styles.progressContainer} ${showControls || !isPlaying ? styles.visible : ''}`}
              onMouseEnter={showVideoControls}
              onMouseLeave={hideVideoControls}
            >
              <div className={styles.progressBar} onClick={handleProgressClick}>
                <LinearProgress
                  variant="determinate"
                  value={progress}
                  className={styles.progress}
                />
              </div>
              <div className={styles.timeDisplay}>
                <span className={styles.currentTime}>{formatTime(currentTime)}</span>
                <span className={styles.duration}>/{formatTime(duration)}</span>
              </div>
              
              {/* 键盘快捷键提示 */}
              {showControls && (
                <div className={styles.keyboardHints}>
                  <span>← → 快进/后退 | 空格 播放/暂停</span>
                </div>
              )}
            </div>
          </div>
        );
      }
    }
    
    return null;
  };

  // 图片轮播组件会自己处理加载失败的情况，这里不再需要单独处理

  return (
    <Card className={styles.card}>
      <div className={styles.mediaContainer}>
        {/* 媒体内容 */}
        {renderMedia()}
      </div>

      {/* 内容信息覆盖层 */}
      <div className={styles.overlay}>
        {/* 用户信息 */}
        <div className={styles.userInfo}>
          <Avatar
            src={content.userAvatar}
            alt={content.username}
            className={styles.avatar}
          />
          <Box>
            <Typography variant="body1" className={styles.username}>
              {content.username}
            </Typography>
          </Box>
        </div>

        {/* 内容标题 */}
        <Typography variant="h6" className={styles.title}>
          {content.title}
        </Typography>

        {/* 内容描述 */}
        {content.textContent && (
          <Typography variant="body2" className={styles.description}>
            {content.textContent}
          </Typography>
        )}

        {/* 统计信息 */}
        <div className={styles.stats}>
          <div className={styles.statItem}>
            <Favorite className={styles.statIcon} />
            <Typography variant="body2">
              {formatNumber(likeCount)}
            </Typography>
          </div>
          <div className={styles.statItem}>
            <Comment className={styles.statIcon} />
            <Typography variant="body2">
              {formatNumber(content.commentCount)}
            </Typography>
          </div>
          <div className={styles.statItem}>
            <Visibility className={styles.statIcon} />
            <Typography variant="body2">
              {formatNumber(content.viewCount)}
            </Typography>
          </div>
        </div>
      </div>

      {/* 操作按钮 */}
      <div className={styles.actionButtons}>
        <IconButton
          onClick={handleLike}
          disabled={likeLoading}
          className={`${styles.actionButton} ${isLiked ? styles.liked : ''}`}
        >
          {likeLoading ? (
            <CircularProgress size={20} color="inherit" />
          ) : isLiked ? (
            <Favorite />
          ) : (
            <FavoriteBorder />
          )}
        </IconButton>
        
        <IconButton
          onClick={handleShare}
          className={styles.actionButton}
        >
          <Share />
        </IconButton>
      </div>
    </Card>
  );
};

export default RecommendationCard; 